package com.linkoog.devtools.json.file_editer.editer.ui.jsonTree.action;

import com.fasterxml.jackson.databind.JsonNode;
import com.intellij.designer.clipboard.SimpleTransferable;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.ui.treeStructure.Tree;
import com.linkoog.devtools.json.file_editer.editer.ui.JackJsonTreeNode;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.tree.TreePath;
import java.awt.datatransfer.DataFlavor;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CopyKeyAction extends AnAction {

    private final Tree tree;

    public CopyKeyAction(Tree tree) {
        super("拷贝键");
        this.tree = tree;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        TreePath[] paths = tree.getSelectionPaths();
        if (paths != null) {
            List<String> keyList = new ArrayList<>();
            for (TreePath path : paths) {
                JackJsonTreeNode node = (JackJsonTreeNode) path.getLastPathComponent();
                JsonNode jsonNode = node.getJsonNode();
                keyList.add(node.getName().toString());
            }

            CopyPasteManager.getInstance().setContents(new SimpleTransferable(StringUtils.join(", ", keyList), DataFlavor.stringFlavor));
        }
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.BGT;
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        TreePath[] paths = tree.getSelectionPaths();
        boolean visible = true;
        if (Objects.nonNull(paths) && paths.length == 1) {
            TreePath path = paths[0];
            JackJsonTreeNode node = (JackJsonTreeNode) path.getLastPathComponent();
            JsonNode jsonNode = node.getJsonNode();
            if (node.isArrayItem()) {
                visible = false;
            }
        }

        e.getPresentation().setEnabledAndVisible(visible);
    }
}
